﻿using System.Windows;
using System.Windows.Input;
using AEM.Properties;
using AEM.Utils;

namespace AEM
{
    /// <summary>
    /// ModbusPort.xaml 的交互逻辑
    /// </summary>
    public partial class ModbusPort : Window
    {
        public ModbusPort()
        {
            InitializeComponent();
            this.TitleBar.MouseLeftButtonDown += new MouseButtonEventHandler(TitleBar_MouseLeftButtonDown);
            this.btn_save.Click += new RoutedEventHandler(btn_save_Click);
            this.Loaded += new RoutedEventHandler(ModbusPort_Loaded);
        }

        void ModbusPort_Loaded(object sender, RoutedEventArgs e)
        {
            this.port.Text = Settings.Default.Port.ToString();
            this.port.TextChanged += new System.Windows.Controls.TextChangedEventHandler(port_TextChanged);
        }

        void port_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(port.Text.Trim()))
            {
                errmsg.Text = this.TryFindResource("PortEmpty") as string;
            }
            else
            {
                if (!this.port.Text.Trim().isNumeric())
                {
                    this.port.Text = this.port.Text.Substring(0, port.Text.Length - 1);
                    errmsg.Text = string.Format(this.TryFindResource("MustBeNumber") as string, this.TryFindResource("ModbusPort") as string);
                }
            }
        }

        void btn_save_Click(object sender, RoutedEventArgs e)
        {
            errmsg.Text = "";
            if (string.IsNullOrEmpty(this.port.Text.Trim())) { port.Text = "502"; }
            if (!this.port.Text.Trim().isNumeric()) { errmsg.Text = string.Format(this.TryFindResource("MustBeNumber") as string, this.TryFindResource("ModbusPort") as string); return; }

            Settings.Default.Port = this.port.Text.Trim().toNumeric();
            Settings.Default.Save();
            errmsg.Text = (string)this.TryFindResource("SavedSuccessfully");
        }

        void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void sys_button_close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void sys_button_min_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }
    }
}
